const gulp = require('gulp');
const fileinclude = require('gulp-file-include')
const babel = require('gulp-babel');
const sass = require('gulp-sass')(require('sass'))
const browsersync = require("browser-sync").create();
//代码压缩
//html =>gulp-htmlmin
//js => gulp-uglify
//css => gulp-clean-css
const htmlmin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')
const cleancss = require('gulp-clean-css')
const del = require('del')


//html指令  拆分页面结构代码并合并在发布文件夹
gulp.task('html', async () => {
  gulp.src(['./src/*.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: "@file"
    }))
    .pipe(gulp.dest('./dist'))
})
//js指令  将ES6的代码转义成ES5的js代码
gulp.task('js', async () => {
  gulp.src(['./src/javascripts/*.js'])
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(gulp.dest('./dist/javascripts'))
})
//css转义
gulp.task('scss', async () => {
  gulp.src(['./src/scss/*.scss'])
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./dist/css'))
})

//监听
gulp.task('watch', async () => {
  gulp.watch(["./src/**/*.html"], gulp.series("html", browserSyncReload));
  gulp.watch(["./src/javascripts/*.js"], gulp.series("js", browserSyncReload));
  gulp.watch(["./src/scss/*.scss"], gulp.series("scss", browserSyncReload));
})


gulp.task("browserSync", async () => {
  browsersync.init({
    server: {
      baseDir: "./"
    },
    port: 3000
  });
});
function browserSyncReload(done) {
  browsersync.reload();
  done(); 
}
function clearDir(done){
  del(['./dist/**/*'])
  setTimeout(function(){
    done();
  },1000)
}

gulp.task("min" , async () => {
  await gulp.src("./src/*.html")
        .pipe(fileinclude({
              prefix: '@@',
              basepath: '@file'
        }))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest("./dist/"));

  await gulp.src("./src/javascripts/*.js")
        .pipe(babel({
              presets: ['@babel/env']
        }))
        .pipe(uglify())
        .pipe(header( banner , project_msg))
        .pipe( gulp.dest("./dist/javascripts"))

  await gulp.src(["./src/scss/*.scss"])
        // sass : 把scss文件编译成css文件; 
        // 添加 error 事件，让scss报错不终止gulp监听; 
        .pipe(sass().on("error" , sass.logError))
        .pipe(cleancss({compatibility: 'ie8'}))
        // .pipe(header( banner , project_msg))
        .pipe(gulp.dest("./dist/css"));
});
var build = gulp.series(clearDir , "min");
exports.build = build;
gulp.task('default', gulp.series(clearDir,'html', 'js', 'scss', 'watch', 'browserSync'));


